package promotion

import (
	"bp/internal/render"
	"bp/internal/service/param"
	"bp/internal/util"
	promotionGrpc "bp/rpc/gen/mwebapi/mpromotion"
	"context"
)

// 列出可用的促销活动
func (s *PromotionMWebApiImp) ListAvailablePromotions(ctx context.Context, req *promotionGrpc.ListAvailablePromotionsReq) (res *promotionGrpc.ListAvailablePromotionsRes, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	slog.Infof("promotion_imp/query.ListAvailablePromotions=>%+v", req)
	defer render.FriendlyEntityError(&err, EntityName)
	res = &promotionGrpc.ListAvailablePromotionsRes{}
	q := s.dao.Q

	ptr, err := s.VldListAvailablePromotionsReq(ctx, q, req)
	if err != nil {
		return
	}
	promotionPtrs, err := s.entityHub.PromotionService.ListAvailablePromotionsOfUseScene(ctx, q, ptr)
	if err != nil {
		return
	}

	var itemCategoryMap param.EntityIDToItemCategoryConfigurationPtrsMap
	var itemMap param.EntityIDToItemConfigurationPtrsMap
	if req.WithItemCategoryConfs {
		itemCategoryMap, err = s.entityHub.PromotionService.GetMapOfPromotionIDToItemCategoryConfigurationPtrsByPromotionPtrs(ctx, q, promotionPtrs)
		if err != nil {
			return
		}
	}
	if req.WithItemConfs {
		itemMap, err = s.entityHub.PromotionService.GetMapOfPromotionIDToItemConfigurationPtrsByPromotionPtrs(ctx, q, promotionPtrs)
		if err != nil {
			return
		}
	}
	res.Promotions = s.ConvPromotionPtrArrayEntityToPb(itemCategoryMap, itemMap)(promotionPtrs)
	return
}
